package net.ib.mtalk.account;

import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.network.task.AddContactsTask;
import net.ib.mtalk.util.MTalkLogWriter;
import android.accounts.Account;
import android.app.Service;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.content.SyncResult;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.widget.Toast;

public class MTalkSyncServiceAdapter extends Service{
	
	private static SyncAdapterImpl mSyncAdapter = null;

	@Override
	public IBinder onBind(Intent intent) {
		return getSyncAdapter().getSyncAdapterBinder();
	}
	
	private SyncAdapterImpl getSyncAdapter() {
		if (mSyncAdapter == null) {
			mSyncAdapter = new SyncAdapterImpl(this);
		}
		return mSyncAdapter;
	}
	
	private static AccountController mUiController;
	private static Context mContext;
	private static Handler mHandler = new Handler(Looper.getMainLooper()) {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HandlerMsgConst.HANDLER_ALL_ADD_CONTACTS_SUCCESS:
				Toast.makeText(mContext, "HANDLER_ALL_ADD_CONTACTS_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};
	
	public static void performSync(Context context, Account account, Bundle extras, 
			String authority, ContentProviderClient provider, SyncResult syncResult) {
		// addcontact
		mUiController = new AccountController(context, mHandler);
		mUiController.addContacts();
	}
	
	private static class SyncAdapterImpl extends AbstractThreadedSyncAdapter {
		private Context mContext;
		
		public SyncAdapterImpl(Context context) {
			super(context, true);
			mContext = context;
		}

		@Override
		public void onPerformSync(Account account, Bundle extras,
				String authority, ContentProviderClient provider,
				SyncResult syncResult) {
			MTalkLogWriter.d("OnPerformSync, Account Name : " + account.name + " Account Type : " + account.type + ", Authority : " + authority + ", Name : " + getClass().getSimpleName());			
			performSync(mContext, account, extras, authority, provider, syncResult);
		}
		
	}
	

}
